import cv2
from pytesseract import pytesseract, image_to_string, image_to_boxes, image_to_data

pytesseract.tesseract_cmd = 'tesseract'

img = cv2.imread('images/installation_docs.png')
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)


def print_string():
    print(image_to_string(img))


def letter_boxes():
    boxes = image_to_boxes(img)
    hImg, wImg, _ = img.shape
    for box in boxes.splitlines():
        letter, x, y, w, h, _ = box.split(' ')
        x, y, w, h = int(x), int(y), int(w), int(h)
        cv2.rectangle(img, (x, hImg - y), (w, hImg - h), (0, 255, 0), 1)
        cv2.putText(img, letter, (x, hImg - y + 25), cv2.FONT_HERSHEY_PLAIN, 1, (255, 0, 0), 1)
    cv2.imshow('image', img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()


def words_boxes():
    data = image_to_data(img)
    for x, b in enumerate(data.splitlines()):
        row = b.split()
        if x == 0 or len(row) < 12:
            continue
        x, y, w, h, words = int(row[6]), int(row[7]), int(row[8]), int(row[9]), row[11]
        cv2.rectangle(img, (x, y), (w + x, h + y), (0, 255, 0), 1)
        cv2.putText(img, words, (x, y), cv2.FONT_HERSHEY_PLAIN, 1, (255, 0, 0), 1)
    cv2.imshow('image', img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

words_boxes()
